package com.jd.controller;

import com.jd.entity.*;
import com.jd.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.github.wxpay.sdk.WXPayUtil;
import com.jd.util.BigDecimalUtils;
import com.jd.util.IdUtil;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/wxNotifyUrl")
public class NotifyController {
	
	private String charset = "utf-8";

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private OrderService orderService;
	@Autowired
	private RulesService rulesService;
	@Autowired
	private UserService userService;
	@Autowired
	private NameSrevice nameService;
	@Autowired
	private DetailedService detailedService;
	@Autowired
	private TicketService ticketService;
   /*	@Resource
	private BusinessPartnerService businessPartnerService;*/

	/**
	 *
	 * @param request
	 * @param response
	 *
	 * @author
	 * 充值不凡币回调函数
	 */
	@RequestMapping(value="/wx",method = RequestMethod.POST)
	public void wx_notify(HttpServletRequest request,
			HttpServletResponse response){
		try {
			System.out.println("+++++++++++++++++++++++++++wx_notify+++++++++++++++++++++++++");
			System.out.println("+++++++++++++++++++++++++++wx_notify+++++++++++++++++++++++++");
		
			InputStream inStream = request.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
			outSteam.close();
			inStream.close();
			String xml  = new String(outSteam.toByteArray(),"utf-8");
			Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);
			String out_trade_no = notifyMap.get("out_trade_no");
			String total_fee = notifyMap.get("total_fee");
			String money = BigDecimalUtils.divideBigDecimal(total_fee,"100");
			System.out.println("+++++++++++++++++++++++++++++++++++++++++:");
			System.out.println(out_trade_no);
			System.out.println(money);
			System.out.println(notifyMap.get("return_code"));

			System.out.println("+++++++++++++++++++++++++++wx_notify+++++++++++++++++++++++++"+notifyMap.get("result_code"));
			if(notifyMap.get("return_code").equals("SUCCESS")){
				try {
					String s = this.signVerifiedIsTrue(out_trade_no, request, response, money);
					if (s.equals("success")) {
						response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
					} else {
						response.getWriter().println("fail");
						System.out.println("-------------------------------0");
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
			}		   
		} catch (Exception e) {		
			e.printStackTrace();	
		}
	}


	/**
	 * 支付成功后的业务
	 * 
	 */
	private String signVerifiedIsTrue(String out_trade_no, HttpServletRequest request, HttpServletResponse response, String total_amount) {
		String flag = "";
		//根据订单号查询订单
		OrderEntity order = orderService.selOrder(out_trade_no);
		RulesEntity rules = rulesService.getRules();
		BigDecimal money = order.getPrice();
		//订单金额格式化
		BigDecimal multiplyOrder = money.multiply(new BigDecimal(100));
		System.out.println("模拟订单价格单位分++++++++++++++"+multiplyOrder);
		System.out.println("模拟订单价格单位分++++++++++++++"+multiplyOrder);
		System.out.println("模拟订单价格单位分++++++++++++++"+multiplyOrder);
		String nowTotalPrice = new DecimalFormat("#0.##").format(multiplyOrder);
		//传入钱数格式化
		BigDecimal totalAmount = new BigDecimal(total_amount);
		BigDecimal multiplyMoney = totalAmount.multiply(new BigDecimal(100));
		String nowTotalMoney = new DecimalFormat("#0.##").format(multiplyMoney);
		System.out.println("订单表中订单价格"+nowTotalPrice);
		System.out.println("订单表中订单价格"+nowTotalPrice);
		System.out.println("订单表中订单价格"+nowTotalPrice);
		System.out.println("除100之后的金额"+nowTotalMoney);
		System.out.println("除100之后的金额"+nowTotalMoney);
		System.out.println("除100之后的金额"+nowTotalMoney);
		//比对回调金额
		if (nowTotalPrice.equals(nowTotalMoney)) {
			//修改订单状态
			Integer i = orderService.updateOrderStatue(order);
			if (i > 0) {
				HashMap<String, Object> user = userService.getUserCode(order.getUserId());
				DetailedEntity detailedEntity = new DetailedEntity();
				detailedEntity.setTitle("充值");
				detailedEntity.setType("0");
				detailedEntity.setFlag("0");
				detailedEntity.setDelflag("0");

				//不凡币比例*金额 = 不凡币数量
				BigDecimal bfb = multiplyMoney.multiply(new BigDecimal(rules.getRemark4()));
				System.out.println("不凡币比例*金额 = 不凡币数量"+nowTotalMoney);
				System.out.println("不凡币比例*金额 = 不凡币数量"+nowTotalMoney);

				//累计获得不凡币 还是原来的不便
				Double accumulatedAmount = Double.valueOf(user.get("accumulated_amount").toString());
				//当前不凡币
				Double balance = Double.valueOf(user.get("mBalance").toString()) + bfb.doubleValue();

				//更新用户总余额
				//userService.updateTotalBalance(bfb,order.getUserId());

				//修改钱包余额
				HashMap<String, Object> balanceMap = new HashMap<String, Object>();
				balanceMap.put("userId", order.getUserId());
				balanceMap.put("balance", balance);
				balanceMap.put("accumulatedAmount", accumulatedAmount);
				Boolean updateTBalance = userService.updateMBalance(balanceMap);

				//插入明细
				if (updateTBalance) {
					detailedEntity.setMoney(bfb);//购买的不凡币数量
					detailedEntity.setId(IdUtil.getIdByUUId());
					detailedEntity.setUserId(order.getUserId());
					detailedEntity.setOperationTime(new Date());
					detailedEntity.setCreateBy(order.getUserId());
					detailedEntity.setCreateTime(new Date());
					detailedService.save(detailedEntity);
					flag = "success";
					System.out.println(flag);
				}
			}
		}
		return flag;
	}
}